#!/usr/bin/env python3
"""
RK3588 ESP32传感器控制系统主程序
"""

import time
import sys
import signal
from esp32_comm import ESP32Communicator
from sensor_manager import SensorManager, SensorReading

class ESP32SensorSystem:
    """ESP32传感器系统主控制器"""
    
    def __init__(self, port: str = '/dev/ttyUSB0'):
        self.port = port
        self.esp32 = ESP32Communicator(port)
        self.sensor_mgr = None
        self.running = False
        
        # 设置信号处理
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
    
    def _signal_handler(self, signum, frame):
        """信号处理函数"""
        print(f"\n收到信号 {signum}，正在关闭系统...")
        self.shutdown()
        sys.exit(0)
    
    def initialize(self) -> bool:
        """初始化系统"""
        print("=== RK3588 ESP32传感器控制系统 ===")
        print(f"正在连接ESP32 ({self.port})...")
        
        if not self.esp32.connect():
            print("❌ 连接ESP32失败")
            return False
        
        print("✅ ESP32连接成功")
        
        # 获取ESP32信息
        info = self.esp32.get_info()
        if info:
            print(f"📱 ESP32信息: {info['info']}")
        
        # 创建传感器管理器
        self.sensor_mgr = SensorManager(self.esp32, self._on_sensor_data)
        
        print("🚀 系统初始化完成")
        return True
    
    def _on_sensor_data(self, reading: SensorReading):
        """传感器数据回调"""
        # 这里可以添加数据处理逻辑
        # 例如：异常检测、数据上报等
        
        # 简单的温度报警
        if reading.temperature and reading.temperature > 30:
            print(f"⚠️  温度警报: {reading.temperature}°C")
        
        # 简单的湿度报警
        if reading.humidity and reading.humidity > 80:
            print(f"⚠️  湿度警报: {reading.humidity}%")
    
    def run_interactive_mode(self):
        """运行交互模式"""
        print("\n=== 交互模式 ===")
        print("命令列表:")
        print("  1 - 读取传感器数据")
        print("  2 - 开始监控")
        print("  3 - 停止监控")
        print("  4 - 控制LED开")
        print("  5 - 控制LED关")
        print("  6 - 获取统计信息")
        print("  7 - 保存数据")
        print("  8 - 重启ESP32")
        print("  q - 退出")
        
        self.running = True
        
        while self.running:
            try:
                cmd = input("\n请输入命令: ").strip()
                
                if cmd == '1':
                    self._read_sensor_data()
                elif cmd == '2':
                    self._start_monitoring()
                elif cmd == '3':
                    self._stop_monitoring()
                elif cmd == '4':
                    self._control_led(True)
                elif cmd == '5':
                    self._control_led(False)
                elif cmd == '6':
                    self._show_statistics()
                elif cmd == '7':
                    self._save_data()
                elif cmd == '8':
                    self._reset_esp32()
                elif cmd.lower() == 'q':
                    break
                else:
                    print("❌ 无效命令")
                    
            except KeyboardInterrupt:
                break
            except Exception as e:
                print(f"❌ 执行命令时出错: {e}")
    
    def _read_sensor_data(self):
        """读取传感器数据"""
        print("📊 读取传感器数据...")
        reading = self.sensor_mgr.read_current_data()
        if reading:
            print(f"🌡️  温度: {reading.temperature}°C")
            print(f"💧 湿度: {reading.humidity}%")
            print(f"💡 LED状态: {'ON' if reading.led_state else 'OFF'}")
        else:
            print("❌ 读取失败")
    
    def _start_monitoring(self):
        """开始监控"""
        try:
            interval = float(input("请输入监控间隔(秒，默认5): ") or "5")
            self.sensor_mgr.start_monitoring(interval)
            print("✅ 监控已开始")
        except ValueError:
            print("❌ 无效的间隔时间")
    
    def _stop_monitoring(self):
        """停止监控"""
        self.sensor_mgr.stop_monitoring()
        print("✅ 监控已停止")
    
    def _control_led(self, state: bool):
        """控制LED"""
        action = "开启" if state else "关闭"
        print(f"💡 {action}LED...")
        if self.sensor_mgr.control_led(state):
            print(f"✅ LED已{action}")
        else:
            print(f"❌ LED{action}失败")
    
    def _show_statistics(self):
        """显示统计信息"""
        print("📈 统计信息:")
        stats = self.sensor_mgr.get_statistics()
        if stats:
            print(f"  总读数: {stats.get('total_readings', 0)}")
            
            if 'temperature' in stats:
                temp_stats = stats['temperature']
                print(f"  温度: {temp_stats['min']:.1f}°C ~ {temp_stats['max']:.1f}°C "
                      f"(平均: {temp_stats['avg']:.1f}°C)")
            
            if 'humidity' in stats:
                hum_stats = stats['humidity']
                print(f"  湿度: {hum_stats['min']:.1f}% ~ {hum_stats['max']:.1f}% "
                      f"(平均: {hum_stats['avg']:.1f}%)")
        else:
            print("  暂无数据")
    
    def _save_data(self):
        """保存数据"""
        filename = input("请输入文件名(默认sensor_data.json): ").strip() or "sensor_data.json"
        self.sensor_mgr.save_data_to_file(filename)
    
    def _reset_esp32(self):
        """重启ESP32"""
        confirm = input("确定要重启ESP32吗? (y/N): ").strip().lower()
        if confirm == 'y':
            print("🔄 重启ESP32...")
            if self.sensor_mgr.reset_esp32():
                print("✅ ESP32重启成功")
                time.sleep(2)  # 等待重启完成
            else:
                print("❌ ESP32重启失败")
    
    def run_demo_mode(self):
        """运行演示模式"""
        print("\n=== 演示模式 ===")
        
        try:
            # 1. 读取初始数据
            print("1. 读取初始传感器数据...")
            self._read_sensor_data()
            time.sleep(2)
            
            # 2. 开始监控
            print("\n2. 开始监控传感器数据...")
            self.sensor_mgr.start_monitoring(interval=3.0)
            time.sleep(10)
            
            # 3. LED控制演示
            print("\n3. LED控制演示...")
            for i in range(3):
                print(f"  第{i+1}次: 开启LED")
                self._control_led(True)
                time.sleep(2)
                
                print(f"  第{i+1}次: 关闭LED")
                self._control_led(False)
                time.sleep(2)
            
            # 4. 显示统计信息
            print("\n4. 显示统计信息...")
            self._show_statistics()
            
            # 5. 保存数据
            print("\n5. 保存数据...")
            self.sensor_mgr.save_data_to_file("demo_data.json")
            
            print("\n✅ 演示完成!")
            
        except Exception as e:
            print(f"❌ 演示过程中出错: {e}")
        finally:
            self.sensor_mgr.stop_monitoring()
    
    def shutdown(self):
        """关闭系统"""
        print("\n🔄 正在关闭系统...")
        self.running = False
        
        if self.sensor_mgr:
            self.sensor_mgr.stop_monitoring()
        
        if self.esp32:
            self.esp32.disconnect()
        
        print("✅ 系统已关闭")

def main():
    """主函数"""
    if len(sys.argv) > 1:
        port = sys.argv[1]
    else:
        port = '/dev/ttyUSB0'
    
    system = ESP32SensorSystem(port)
    
    if not system.initialize():
        sys.exit(1)
    
    try:
        # 选择运行模式
        print("\n请选择运行模式:")
        print("1 - 交互模式")
        print("2 - 演示模式")
        
        mode = input("请输入选择 (1/2): ").strip()
        
        if mode == '1':
            system.run_interactive_mode()
        elif mode == '2':
            system.run_demo_mode()
        else:
            print("❌ 无效选择，使用交互模式")
            system.run_interactive_mode()
            
    except Exception as e:
        print(f"❌ 系统运行出错: {e}")
    finally:
        system.shutdown()

if __name__ == "__main__":
    main() 